package Test;

import static org.junit.Assert.*;

import java.io.File;
import java.io.IOException;
import java.util.Arrays;

import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import Calculate.ByteCalc;
import Script.Offset;

public class OffsetTest {
	
	@Test
	public void offsetCanReturnIntValue() {
		Offset offset = new Offset(852480);
		
		assertEquals(852480, offset.getValue());
	}
	
	@Test
	public void offsetCanReturnEvenHexValue() {
		Offset offset = new Offset(14483968);
		
		assertEquals("DD0200", offset.getHex(3));
	}
	
	@Test
	public void offsetCanReturnUnevenHexValue() {
		Offset offset = new Offset(852480);
		
		assertEquals("0D0200", offset.getHex(3));
	}
	
	@Test
	public void canReturnByteSize() {
		Offset offset = new Offset(852480);
		String hexString = offset.getHex(3);
		
		int size = (int) Math.ceil(hexString.length() / 2);
		
		assertEquals(size, 3);
	}
	
	@Test
	public void canSwitch4ByteEndianess() {
		Offset offset = new Offset(287454020); // Hex: 11223344
		offset.switchEndian();
		
		long val = offset.getLongValue(4);
		Offset o = new Offset(val);
		
		assertEquals(o.getHex(4), "44332211");
	}
	
	@Test
	public void canSwitch2ByteEndianess() {
		Offset offset = new Offset(4386); // Hex: 1122
		offset.switchEndian();
		
		long val = offset.getLongValue(2);
		Offset o = new Offset(val);
		
		assertEquals(o.getHex(2), "2211");
	}
	
	@Test
	public void canSwitchEndianessWhenOnlyOneByteIsNotZero() {
		Offset offset = new Offset(4); // Hex: 0004
		offset.switchEndian();
		
		assertEquals(offset.getHex(2), "0400");
	}
	
	@Test
	public void canSwitchEndianessOnArrayContainingOnlyZeros() {
		Offset offset = new Offset(0);
		offset.switchEndian();
		assertEquals(offset.getValue(), 0);
	}
	
	@Test
	public void canCalculateEvenByteSize() {
		Offset offset = new Offset(4386); // Hex: 1122
		
		assertEquals(offset.byteSize(), 2);
	}
	
	@Test
	public void canCalculateUnevenByteSize() {
		Offset offset = new Offset(69922); // Hex: 11122
		
		assertEquals(offset.byteSize(), 3);
	}
	
	@Test
	public void canCreateOffsetFromByteArray() {
		Long offset = Long.parseLong("1122", 16);
		byte[] bytes = ByteCalc.longToByteArray(offset);
		Offset bOff = new Offset(bytes);
			
		assertEquals(bOff.getHex(2), "1122");		
	}
	
	@Test
	public void canTrimOffsetToLong() {
		Offset trim = new Offset(133);
		byte[] b = ByteCalc.longToByteArray(133);
		b = ByteCalc.subArray(b, b.length - 1, b.length);
		
		assertEquals(ByteCalc.byteArrayToLong(b), trim.getLongValue(1));
	}
	
	@Test
	public void canTrimOffsetToByte() {
		Offset trim = new Offset(133);
		byte[] b = ByteCalc.longToByteArray(133);
		b = ByteCalc.subArray(b, b.length - 1, b.length);
		
		assertTrue(Arrays.equals(b, trim.getByteValue(1)));
	}
}
